package com.ds.infrastructure.audit.admin.handler;

import com.ds.infrastructure.audit.common.entity.Result;
import com.ds.infrastructure.audit.common.enums.ResultCode;
import com.ds.infrastructure.audit.common.exception.KbaAuditException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.stream.Collectors;

/**
 * 作用：
 *
 * @author WeiShaoying
 * @date 2020/8/7
 */
@RestControllerAdvice(basePackages = "com.ds.infrastructure.audit.admin.controller")
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 参数异常
     */
    @ResponseStatus(code = HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        String msg = StringUtils.join(e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.toList()), ";");
        log.error("参数校验异常：{}", msg);
        return Result.fail(ResultCode.PARAM_VALIDATE_FAILED.getCode(), msg);
    }

    /**
     * 业务异常
     */
    @ExceptionHandler(KbaAuditException.class)
    public Result businessExceptionHandler(KbaAuditException e) {
        log.error("业务异常：{}", e.getMessage());
        return Result.fail(e.getCode(), e.getMessage());
    }

    /**
     * 权限拒绝异常
     */
    @ExceptionHandler(AccessDeniedException.class)
    public Result accessDeniedExceptionHandler(AccessDeniedException e) {
        log.error("权限拒绝异常：{}", e.getMessage());
        return Result.fail(ResultCode.AUTH_VALIDATE_FAILED.getCode(), e.getMessage());
    }

    /**
     * 默认处理
     *
     * @param response
     * @param ex
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result otherExceptionHandler(HttpServletResponse response, Exception ex) {
        log.error("其它异常：{}", ex.getMessage());
        response.setStatus(ResultCode.SERVER_ERROR.getCode());
        return Result.fail(ResultCode.SERVER_ERROR.getCode(), ex.getMessage());
    }

}
